package com.seeyon.apps.ddkk.manager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.ddkk.utils.ZipUtils;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.BaseManager;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.apps.kk.util.TTUtils;
import com.seeyon.apps.kk.util.WordToPDF;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.dao.EnumItemDAO;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.util.JDBCAgent;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.oainterface.impl.exportdata.FileDownloadExporter;
import com.seeyon.oainterface.impl.exportdata.FileUploadExporter;

public class KkqxbManager extends BaseManager{
	private static final Log log = LogFactory.getLog(KkqxbManager.class);
	private FreemarkFlowManager freemarkFlowManager;
	private FormDataBaseManager kkBaseFormManager;
	private QiangsDDManager qiangsDDManager;
	private AttachmentManager attachmentManager;
	private String oapath=StringUtils.substringBefore(AppContext.getCfgHome().toString(), "WEB-INF");//Seeyon/A8/ApacheJetspeed/webapps/seeyon
	private static String qxbUrl;
	private FileManager fileManager;
	private AttachmentDAO attachmentDAO;
	private FormApi4Cap4 formApi4Cap4;
	private EnumItemDAO newEnumItemDAO;
	
	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}
	public void setNewEnumItemDAO(EnumItemDAO newEnumItemDAO) {
		this.newEnumItemDAO = newEnumItemDAO;
	}


	/**
	 * 企业关键人员信息插入底表
	 * @param companyName 经销商名称
	 * @return 底表数据ID
	 * @author WangTong
	 */
	public void saveEmployees(String companyName,FormBean formBean,FormDataMasterBean formDataMasterBean){
		//根据经销商名称查询启信宝信息
	   JSONObject compayJson=getCompany(companyName);
		/*JSONObject compayJson=new JSONObject();
		String path="dd"+File.separator + "qxb.ftl";
		Map<String, Object> map=new HashMap<String, Object>();
		compayJson=JSONObject.parseObject(this.freemarkFlowManager.fltTemplateIntoString(path,map));*/
		 if(compayJson != null && !compayJson.isEmpty()){
			JSONObject dataObj=compayJson.getJSONObject("data");
			JSONArray  employees=dataObj.getJSONArray("employees");
			log.info("ddkk-关键人员信息："+employees);
			//将经销商主要人员信息保存至底表
			if(employees != null){
				for (int i = 0; i < employees.size(); i++) {
					JSONObject employeeObj=employees.getJSONObject(i);
//					if(!"监事".equals(employeeObj.getString("job_title"))){
						try {
							Map<String, Object> dataMap=new HashMap<String, Object>();
							dataMap.put("姓名", employeeObj.getString("name"));
							dataMap.put("职位", employeeObj.getString("job_title"));
							dataMap.put("经销商名称", companyName);
							Long dataId=kkBaseFormManager.saveUnflowData(Constants.keyMemberCode, Constants.createUser,dataMap);
							qiangsDDManager.createFormRelation(formBean, formDataMasterBean, Constants.keyMemberCode, dataId);
						} catch (Exception e) {
							log.error("kk-保存关键人员底表出错：", e);
						}
//					}else{
//						log.info("kk-保存关键人员底表，去除监事人员："+employeeObj);
//					}
				}
			}
			JSONArray  partners=dataObj.getJSONArray("partners");
			log.info("ddkk-股东信息："+partners);
			//将经销商股东信息保存至底表
			if(partners != null){
				for (int i = 0; i < partners.size(); i++) {
					JSONObject partnerObj=partners.getJSONObject(i);
					if("自然人股东".equals(partnerObj.getString("stock_type"))||partnerObj.getString("name").length()<=5){
						try {
							Map<String, Object> dataMap=new HashMap<String, Object>();
							dataMap.put("姓名", partnerObj.getString("name"));
							dataMap.put("职位", "股东");
							dataMap.put("经销商名称", companyName);
							Long dataId=kkBaseFormManager.saveUnflowData(Constants.keyMemberCode, Constants.createUser, dataMap);
							qiangsDDManager.createFormRelation(formBean, formDataMasterBean, Constants.keyMemberCode, dataId);
						} catch (Exception e) {
							log.error("kk-保存关键人员底表出错：", e);
						} 
					}
				}
			}
			
		}
	}
	/**
	 * 保存经销商默认关键人员信息到底表，并将数据ID回传到表单
	 * @throws BusinessException 
	 * @throws NumberFormatException 
	 */
	public void saveDefaultEmployees(String companyName, FormBean formBean,FormDataMasterBean formDataMasterBean) throws NumberFormatException, BusinessException{
		String path="dd"+File.separator + "defaultEmployee.ftl";
		String[] compayAry=this.freemarkFlowManager.fltTemplateIntoString(path,null).split(",");
		log.info("ddkk:产品线名称："+formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("产品线缩写").getName()));
		String cpx=formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("产品线缩写").getName()).toString();
		//String jxsdj=enumItemDAO.findById(Long.valueOf(formDataMasterBean.getFieldValue(formBean.getFieldBeanByDisplay("经销商等级").getName()).toString())).getShowvalue();
		boolean isBX=("BS".equals(cpx));
		//倍绣产品    强生签约服务商  一级经销商
		    Long[] dataAry=new Long[compayAry.length];
			for (int i = 0; i < compayAry.length; i++) {
				if(isBX && "企业负责人".equals(compayAry[i])){
					continue;
				}
				try {
					Map<String, Object> dataMap=new HashMap<String, Object>();
					dataMap.put("姓名", compayAry[i]);
					dataMap.put("职位", compayAry[i]);
					dataMap.put("经销商名称", companyName);
				    Long dataId=kkBaseFormManager.saveUnflowData(Constants.keyMemberCode,Constants.createUser,dataMap);
				    dataAry[i]=dataId;
				    this.qiangsDDManager.createFormRelation(formBean, formDataMasterBean, Constants.keyMemberCode, dataId);
				} catch (Exception e) {
					log.error("kk-保存默认关键人员底表出错：", e);
				} 
			}
			//将数据ID挂载到表单上
			formDataMasterBean.addFieldValue(formBean.getFieldBeanByDisplay("公司负责人底表ID").getName(), 
					dataAry[0]);
			formDataMasterBean.addFieldValue(formBean.getFieldBeanByDisplay("业务负责人底表ID").getName(), 
					dataAry[1]);
			if(!isBX){
				formDataMasterBean.addFieldValue(formBean.getFieldBeanByDisplay("医疗器械许可人底表ID").getName(), 
						dataAry[2]);
			}			
	}
	
	/**
	 * 根据企业详细名称查询企业详情信息
	 * @param keyword 企业名称
	 * @return 企业信息
	 * @author WangTong
	 */
	public  JSONObject getCompany(String keyword){
		//启信宝调用日志
		Map<String, Object> logMap=new HashMap<String, Object>();
		logMap.put("接口名称", "启信宝关键人员接口调用");
		logMap.put("调用模块", "启信宝接口");//致远插件、启信宝接口
		logMap.put("调用人", AppContext.getCurrentUser()==null?"":AppContext.getCurrentUser().getName());
		logMap.put("经销商名称", keyword);
		logMap.put("调用时间", new Date());
		//调用启信宝查询接口
		try {
			log.info("kk企信宝查询："+keyword);
			keyword=URLEncoder.encode(keyword, "utf-8");
			String result=TTUtils.ttGet(qxbUrl+keyword);
			JSONObject resultObj=(JSONObject) JSONObject.parse(result);
			String state = resultObj.getString("status");
			if (!("200".equals(state))) {
				log.info("kk企信宝查询返回异常："+resultObj.get("message").toString());
				logMap.put("调用状态", "失败");
				logMap.put("失败说明", resultObj.get("message").toString());
			}else{
				logMap.put("调用状态", "成功");
			}
			try {
				kkBaseFormManager.saveUnflowData(Constants.qxbLogformCode,Constants.createUser, logMap);
			} catch (Exception e) {
				log.error("ddkk-启信宝调用日志保存失败：", e);
			} 
			return resultObj;
		} catch (UnsupportedEncodingException e) {
			log.error("kk企信宝查询异常：", e);
			logMap.put("调用状态", "异常");
			logMap.put("失败说明",e.toString());
			try {
				kkBaseFormManager.saveUnflowData(Constants.qxbLogformCode,Constants.createUser, logMap);
			} catch (Exception e2) {
				log.error("ddkk-启信宝调用日志保存失败：", e2);
			} 
		}
		return null;
	}
	/**
	 * 经销商表单附件下载打包
	 * @param formDataBean 经销商流程表数据
	 * @param list	关键人员信息底表数据
	 * @throws Exception
	 */
	public void ddfileDownload(FormDataMasterBean formDataBean,List<FormDataMasterBean> list,Long summaryId) throws Exception{
		String savepath=oapath+File.separator+"ddkkfile"+File.separator+formDataBean.getId();
		//获取所有需要下载的附件字段
		JSONArray attrAry=new JSONArray();
		String path="dd"+File.separator + "attr.ftl";
		attrAry=JSONArray.parseArray(this.freemarkFlowManager.fltTemplateIntoString(path,null));
		//下载
		for (int i = 0; i < attrAry.size(); i++) {
			String ddkksavepath=savepath;
			JSONObject attrObj=attrAry.getJSONObject(i);
				if("1".equals(attrObj.getString("form"))){//经销商流程表
					ddkksavepath=savepath+File.separator+attrObj.getString("source")+File.separator;
					FormFieldBean formFieldBean=formDataBean.getFormTable().getFieldBeanByDisplay(attrObj.getString("fieldName"));
					Long subreference=formDataBean.getFieldValue(formFieldBean.getName())!=null?Long.valueOf(formDataBean.getFieldValue(formFieldBean.getName()).toString()):null;
					if(subreference!=null){
						fileDownload(subreference, ddkksavepath,attrObj);
					}
				}else if("2".equals(attrObj.getString("form"))){//关键人员简历底表
					if(!list.isEmpty()){
						for (int j = 0; j < list.size(); j++) {
							ddkksavepath=savepath+File.separator+attrObj.getString("source")+File.separator;
							FormFieldBean formFieldBean=list.get(j).getFormTable().getFieldBeanByDisplay(attrObj.getString("fieldName"));
							Long subreference=list.get(j).getFieldValue(formFieldBean.getName())!=null?Long.valueOf(list.get(j).getFieldValue(formFieldBean.getName()).toString()):null;
							if(subreference!=null){
								attrObj.put("memberName", list.get(j).getFieldValue(list.get(j).getFormTable().getFieldBeanByDisplay("姓名").getName()));
																	
								BigDecimal enumId = new BigDecimal(list.get(j).getFieldValue(list.get(j).getFormTable().getFieldBeanByDisplay("是否曾任政府官员").getName()).toString());
			                    String enumvalue =this.newEnumItemDAO.findById(enumId.longValue()).getEnumvalue();
								if(attrObj.getString("fieldName").equals("曾任声明附件")&&"1".equals(enumvalue)){
									continue;
								}
								fileDownload(subreference, ddkksavepath,attrObj);
							}
						}
					}
				}
		}
			//将所有附件打包
			String attrPath=savepath+".zip";
			ZipUtils.zip(savepath, attrPath);
			//上传附件并挂载到表单上
			FileUploadExporter uploadExporter = new FileUploadExporter();
			String fileurlsy = uploadExporter.processUpload(Constants.createUser,new String[] {attrPath}); 
			V3XFile vfile = fileManager.getV3XFile(Long.valueOf(fileurlsy));
			//表单附件框挂载的id
			Long attId = UUIDLong.longUUID();
			Attachment att = new Attachment(vfile);
			att.setReference(summaryId);
			att.setCategory(66);
			att.setSubReference(attId);
			att.setIdIfNew();
			att.setFilename("全部文件.zip");
			attachmentDAO.save(att);
			//将附件ID挂载到表单上
			Map<String, Object> fileMap=new HashMap<String, Object>();
			fileMap.put("一键下载附件", attId);
			kkBaseFormManager.updateFormData(Constants.ddApplyCode, formDataBean, fileMap);

	}
	/**
	 * OA表单控件附件下载
	 * @param subreference
	 * @param savePath
	 * @throws Exception
	 */
	public void fileDownload(Long subreference,String savePath,JSONObject attrObj) throws Exception{
		List<Long> attachmentlist=this.attachmentManager.getBySubReference(subreference);
        for (int i = 0; i < attachmentlist.size(); i++) {
    	 String fileUrl=attachmentlist.get(i).toString();
    	 String fileName=this.attachmentManager.getAttachmentByFileURL(attachmentlist.get(i)).getFilename();
    	 //人员简历底表附件名称加上人员姓名
    	 if("2".equals(attrObj.getString("form"))){
    		 fileName=attrObj.getString("memberName")+"_"+fileName;
    	 }else{
    		 fileName=attrObj.getString("fieldName").replaceAll("附件", "")+"_"+fileName;
    	 }
    	 if(!new File(savePath).exists()){
		  new File(savePath).mkdirs(); 
		 }    		 
		 FileOutputStream out = new FileOutputStream(savePath+fileName);
		 FileDownloadExporter downloadExporter = new FileDownloadExporter();
		 //将附件下载到seeyon目录下的pdfsy目录
		 downloadExporter.processDownload(fileUrl, out);
		 out.close();
		 if("true".equals(attrObj.getString("istoPdf"))){
			String pdffileName =StringUtils.substringBefore(fileName, ".")+".pdf";
			WordToPDF.wordToPDF(savePath+fileName, savePath+pdffileName);
			//转完pdf后删除word文件
			FileUtils.deleteQuietly(new File(savePath+fileName));
		 }
       } 
	}
	/**
	 * 将syncDDBasicInfo中的附件转换为二进制代码存储到数据库表中
	 */
	public void syncDDBasicInfo(){
		log.info("ddkk-syncDDBasicInfo附件转换二进制代码 strat");
        //查询DDDistributorBasicInfo底表
		List<Map> list=new ArrayList<Map>();
		FormBean bean = new FormBean();
		try {
			bean = formApi4Cap4.getFormByFormCode(Constants.DDBasicInfo);
			StringBuilder sql = new StringBuilder();
			sql.append("select * from "+bean.getMasterTableBean().getTableName() +" where (");
			sql.append(bean.getFieldBeanByDisplay("ThreeCertificatepicFileStream").getName() +" is not null and ThreeCertificatepicFileStream is  null ) or (");
			sql.append(bean.getFieldBeanByDisplay("LicensepicFileStream").getName() +" is not null and LicensepicFileStream is  null ) or (");
			sql.append(bean.getFieldBeanByDisplay("OrganizationCCpicFileStream").getName() +" is not null and OrganizationCCpicFileStream is  null ) or (");
			sql.append(bean.getFieldBeanByDisplay("TaxRegistrationpicFileStream").getName() +" is not null and TaxRegistrationpicFileStream is  null ) or (");
			sql.append(bean.getFieldBeanByDisplay("MedicalDevicesLicensepicFileStream").getName() +" is not null and MedicalDevicesLicensepicFileStream is  null ) or (");
			sql.append(bean.getFieldBeanByDisplay("BiosealpicFileStream").getName() +" is not null and BiosealpicFileStream is  null )");
			list=JdbcAgentUtil.doQuery(sql.toString(), null);
		} catch (BusinessException e) {
			log.error("ddkk-DDDistributorBasicInfo文件二进制转换查询出错：",e);
		}
		if(!list.isEmpty()){
			for (int i = 0; i < list.size(); i++) {
					try {
						StringBuilder updateSql = new StringBuilder();
						updateSql.append("update "+bean.getMasterTableBean().getTableName()+" set state="+list.get(i).get("state"));
						List<InputStream> updatelist=new ArrayList<InputStream>();
						//三证合一
						if(list.get(i).get(bean.getFieldBeanByDisplay("ThreeCertificatepicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("ThreeCertificatepicFileStream").getName()));
							updateSql.append(" ,ThreeCertificatepicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));
						}
						//营业执照
						if(list.get(i).get(bean.getFieldBeanByDisplay("LicensepicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("LicensepicFileStream").getName()));
							updateSql.append(" ,LicensepicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));						
						}
						//组织机构代码证
						if(list.get(i).get(bean.getFieldBeanByDisplay("OrganizationCCpicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("OrganizationCCpicFileStream").getName()));
							updateSql.append(" ,OrganizationCCpicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));						
						}
						//税务登记号
						if(list.get(i).get(bean.getFieldBeanByDisplay("TaxRegistrationpicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("TaxRegistrationpicFileStream").getName()));
							updateSql.append(" ,TaxRegistrationpicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));						
						}
						//医疗器械许可证
						if(list.get(i).get(bean.getFieldBeanByDisplay("MedicalDevicesLicensepicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("MedicalDevicesLicensepicFileStream").getName()));
							updateSql.append(" ,MedicalDevicesLicensepicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));						
						}
						//药品经营许可证
						if(list.get(i).get(bean.getFieldBeanByDisplay("BiosealpicFileStream").getName())!=null){
							List<Long> attachmentlist=this.attachmentManager.getBySubReference(MapUtils.getLong(list.get(i), bean.getFieldBeanByDisplay("BiosealpicFileStream").getName()));
							updateSql.append(" ,BiosealpicFileStream= ?");				
							updatelist.add(this.fileManager.getFileInputStream(attachmentlist.get(0)));						
						}
						 updateSql.append(" where id="+list.get(i).get("id"));
						 LobHandler lobHandler = new DefaultLobHandler();
						 AbstractLobCreatingPreparedStatementCallback callback = new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
							@Override
							protected void setValues(PreparedStatement statement,
									LobCreator paramLobCreator) throws SQLException,
									DataAccessException {
								for (int j = 0; j < updatelist.size(); j++) {
									statement.setBinaryStream(j+1, updatelist.get(j));
								}
							}
						};
						 JDBCAgent.executePreparedStatement(updateSql.toString(),callback);
					} catch (Exception e) {
						log.error("ddkk-DDDistributorBasicInfo文件二进制转换更新出错：", e);
					} 
					
			}
		}
		log.info("ddkk-syncDDBasicInfo附件转换二进制代码 end");
		log.info("ddkk-syncDDDistributor合并文件名称同步开始");
		 //查询DDDistributor底表
		List<Map> ddList=new ArrayList<Map>();
		FormBean ddbean = new FormBean();
		try {
			ddbean = formApi4Cap4.getFormByFormCode(Constants.ddDistributor);
			StringBuilder sql = new StringBuilder();
			sql.append("select * from "+ddbean.getMasterTableBean().getTableName() +" where (");
			sql.append(ddbean.getFieldBeanByDisplay("AssessOriginalFileName").getName() +" is not null and "+ddbean.getFieldBeanByDisplay("AssessNewFileName").getName()+" is  null ) or (");
			sql.append(ddbean.getFieldBeanByDisplay("QAExamineOriginalFileName").getName() +" is not null and "+ddbean.getFieldBeanByDisplay("QAExamineNewFileName").getName()+" is  null ) or (");
			sql.append(ddbean.getFieldBeanByDisplay("BUExamineOriginalFileName").getName() +" is not null and "+ddbean.getFieldBeanByDisplay("BUExamineNewFileName").getName()+" is  null )");
			ddList=JdbcAgentUtil.doQuery(sql.toString(), null);
		} catch (BusinessException e) {
			log.error("ddkk-DDDistributorBasicInfo文件二进制转换查询出错：",e);
		}
		if(!ddList.isEmpty()){
			for (int i = 0; i < ddList.size(); i++) {
			try {
				StringBuilder updateSql = new StringBuilder();
				updateSql.append("update "+ddbean.getMasterTableBean().getTableName()+" set state="+ddList.get(i).get("state"));
				List<String> updatelist=new ArrayList<String>();
				//AssessOriginalFileName
				if(ddList.get(i).get(ddbean.getFieldBeanByDisplay("AssessOriginalFileName").getName())!=null){
					updateSql.append(" ,"+ddbean.getFieldBeanByDisplay("AssessNewFileName").getName()+"= ?");	
					List<Long> attachmentlistid=this.attachmentManager.getBySubReference(MapUtils.getLong(ddList.get(i), ddbean.getFieldBeanByDisplay("AssessOriginalFileName").getName()));
					List<Attachment> attachmentList=this.attachmentManager.getAttachmentByFileURLs(attachmentlistid);
					String fileName="";
					int i1=0;
					for (Attachment att : attachmentList) {
						fileName+=i1==0?att.getFilename():"，"+att.getFilename();
						i1++;
					}
					updatelist.add(fileName);
					
				}
				//QAExamineOriginalFileName
				if(ddList.get(i).get(ddbean.getFieldBeanByDisplay("QAExamineOriginalFileName").getName())!=null){
					updateSql.append(" ,"+ddbean.getFieldBeanByDisplay("QAExamineNewFileName").getName()+"= ?");
					List<Long> attachmentlistid=this.attachmentManager.getBySubReference(MapUtils.getLong(ddList.get(i), ddbean.getFieldBeanByDisplay("QAExamineOriginalFileName").getName()));
					List<Attachment> attachmentList=this.attachmentManager.getAttachmentByFileURLs(attachmentlistid);
					String fileName="";
					int i1=0;
					for (Attachment att : attachmentList) {
						fileName+=i1==0?att.getFilename():"，"+att.getFilename();
						i1++;
					}
					updatelist.add(fileName);
				}
				//BUExamineOriginalFileName
				if(ddList.get(i).get(ddbean.getFieldBeanByDisplay("BUExamineOriginalFileName").getName())!=null){
					updateSql.append(" ,"+ddbean.getFieldBeanByDisplay("BUExamineNewFileName").getName()+"= ?");
					List<Long> attachmentlistid=this.attachmentManager.getBySubReference(MapUtils.getLong(ddList.get(i), ddbean.getFieldBeanByDisplay("BUExamineOriginalFileName").getName()));
					List<Attachment> attachmentList=this.attachmentManager.getAttachmentByFileURLs(attachmentlistid);
					String fileName="";
					int i1=0;
					for (Attachment att : attachmentList) {
						fileName+=i1==0?att.getFilename():"，"+att.getFilename();
						i1++;
					}
					updatelist.add(fileName);
				}
				updateSql.append(" where id="+ddList.get(i).get("id"));
				  JdbcAgentUtil.doUpdateOrInsert(updateSql.toString(), updatelist);
				} catch (BusinessException e) { 
					log.error("ddkk:合并syncDDDistributor文件名异常", e);
				}
			}
		}
		log.info("ddkk-syncDDDistributor合并文件名称同步结束");
	}
	
	
	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}
	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}
	public AttachmentManager getAttachmentManager() {
		return attachmentManager;
	}
	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}
	public String getQxbUrl() {
		return qxbUrl;
	}
	public void setQxbUrl(String qxbUrl) {
		this.qxbUrl = qxbUrl;
	}
	public FileManager getFileManager() {
		return fileManager;
	}
	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}
	public AttachmentDAO getAttachmentDAO() {
		return attachmentDAO;
	}
	public void setAttachmentDAO(AttachmentDAO attachmentDAO) {
		this.attachmentDAO = attachmentDAO;
	}
	public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
		this.kkBaseFormManager = kkBaseFormManager;
	}
	public void setQiangsDDManager(QiangsDDManager qiangsDDManager) {
		this.qiangsDDManager = qiangsDDManager;
	}
	
}
